package model

import (
	"gorm.io/gorm"
	"time"
)

// PrescriptionRequest 开药申请表
type PrescriptionRequest struct {
	ID                   int64          `gorm:"primaryKey;autoIncrement" json:"id"`
	UserID               int64          `gorm:"index;not null;comment:用户ID" json:"userId"`
	PatientID            int64          `gorm:"index;not null;comment:患者ID" json:"patientId"`
	DoctorID             int64          `gorm:"index;comment:医生ID" json:"doctorId"`
	SymptomDescription   string         `gorm:"type:text;comment:症状描述" json:"symptomDescription"`
	PrescriptionImageUrl string         `gorm:"type:varchar(500);comment:处方照片URL" json:"prescriptionImageUrl"`
	Status               int            `gorm:"type:tinyint;default:1;comment:状态 1:待选择医生 2:待支付 3:待审核 4:已通过 5:已拒绝" json:"status"`
	TotalAmount          float64        `gorm:"type:decimal(10,2);default:0;comment:总金额" json:"totalAmount"`
	OrderID              int64          `gorm:"index;comment:订单ID" json:"orderId"`
	CreatedAt            time.Time      `json:"createdAt"`
	UpdatedAt            time.Time      `json:"updatedAt"`
	DeletedAt            gorm.DeletedAt `gorm:"index" json:"-"`
}

func (PrescriptionRequest) TableName() string {
	return "prescription_requests"
}

// PrescriptionMedicine 开药申请药品明细表
type PrescriptionMedicine struct {
	ID                    int64          `gorm:"primaryKey;autoIncrement" json:"id"`
	PrescriptionRequestID int64          `gorm:"index;not null;comment:开药申请ID" json:"prescriptionRequestId"`
	MedicineID            int64          `gorm:"index;not null;comment:药品ID" json:"medicineId"`
	MedicineName          string         `gorm:"type:varchar(100);not null;comment:药品名称" json:"medicineName"`
	Quantity              int            `gorm:"not null;comment:数量" json:"quantity"`
	Price                 float64        `gorm:"type:decimal(10,2);not null;comment:单价" json:"price"`
	Dosage                string         `gorm:"type:varchar(200);comment:用法用量" json:"dosage"`
	CreatedAt             time.Time      `json:"createdAt"`
	DeletedAt             gorm.DeletedAt `gorm:"index" json:"-"`
}

func (PrescriptionMedicine) TableName() string {
	return "prescription_medicines"
}

// ==================== PrescriptionRequest 模型方法 ====================

// Create 创建开药申请
func (p *PrescriptionRequest) Create(db *gorm.DB) error {
	p.CreatedAt = time.Now()
	p.UpdatedAt = time.Now()
	return db.Create(p).Error
}

// GetByID 根据ID获取开药申请详情
func (p *PrescriptionRequest) GetByID(db *gorm.DB, id, userID int64) error {
	return db.Where("id = ? AND user_id = ?", id, userID).First(p).Error
}

// GetListByUserID 获取用户的开药申请列表
func GetPrescriptionRequestListByUserID(db *gorm.DB, userID int64, status, page, pageSize int) ([]PrescriptionRequest, int64, error) {
	var requests []PrescriptionRequest
	var total int64

	query := db.Model(&PrescriptionRequest{}).Where("user_id = ?", userID)
	if status > 0 {
		query = query.Where("status = ?", status)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	err := query.Scopes(Paginate(page, pageSize)).
		Order("id DESC").
		Find(&requests).Error

	return requests, total, err
}

// SelectDoctor 选择开药医生
func (p *PrescriptionRequest) SelectDoctor(db *gorm.DB, doctorID int64) error {
	return db.Model(p).Updates(map[string]interface{}{
		"doctor_id":  doctorID,
		"status":     2, // 待支付
		"updated_at": time.Now(),
	}).Error
}

// UpdateStatus 更新开药申请状态
func (p *PrescriptionRequest) UpdateStatus(db *gorm.DB, status int) error {
	return db.Model(p).Updates(map[string]interface{}{
		"status":     status,
		"updated_at": time.Now(),
	}).Error
}

// CalculateTotalAmount 计算总金额
func (p *PrescriptionRequest) CalculateTotalAmount(db *gorm.DB) error {
	var total float64
	db.Model(&PrescriptionMedicine{}).
		Where("prescription_request_id = ?", p.ID).
		Select("SUM(price * quantity)").
		Scan(&total)
	
	return db.Model(p).Updates(map[string]interface{}{
		"total_amount": total,
		"updated_at":   time.Now(),
	}).Error
}

// ==================== PrescriptionMedicine 模型方法 ====================

// Create 添加药品到处方
func (pm *PrescriptionMedicine) Create(db *gorm.DB) error {
	pm.CreatedAt = time.Now()
	return db.Create(pm).Error
}

// GetByPrescriptionRequestID 获取处方药品列表
func GetPrescriptionMedicineListByRequestID(db *gorm.DB, requestID int64) ([]PrescriptionMedicine, error) {
	var medicines []PrescriptionMedicine
	err := db.Where("prescription_request_id = ?", requestID).Find(&medicines).Error
	return medicines, err
}

// Delete 删除药品
func (pm *PrescriptionMedicine) Delete(db *gorm.DB) error {
	return db.Delete(pm).Error
}

